 // API调用相关函数

// 检查服务状态
async function checkStatus() {
    try {
        const response = await fetch('/api/proxy/status');
        const data = await response.json();
        
        updateProxyServerStatus(data.server_running);
        updateSystemProxyStatus(data.system_proxy);
    } catch (error) {
        console.error('检查状态失败:', error);
    }
}

// 切换代理服务器状态
async function toggleProxyServer() {
    const btnEl = document.getElementById('proxy-server-btn');
    const isRunning = btnEl.textContent === '停止';
    
    try {
        const endpoint = isRunning ? '/api/proxy/stop' : '/api/proxy/start';
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({})
        });
        const data = await response.json();
        
        if (data.success) {
            checkStatus();
        } else {
            alert('操作失败');
        }
    } catch (error) {
        console.error('操作失败:', error);
        alert('操作失败');
    }
}

// 切换系统代理状态
async function toggleSystemProxy() {
    const btnEl = document.getElementById('system-proxy-btn');
    const isEnabled = btnEl.textContent === '禁用';
    
    try {
        const endpoint = isEnabled ? '/api/system-proxy/disable' : '/api/system-proxy/enable';
        const body = isEnabled ? {} : { host: '127.0.0.1', port: 8080 };
        
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body)
        });
        
        const data = await response.json();
        if (data.success) {
            checkStatus();
        } else {
            alert('操作失败');
        }
    } catch (error) {
        console.error('操作失败:', error);
        alert('操作失败');
    }
}

// 加载规则列表
async function loadRules() {
    try {
        const response = await fetch('/api/config');
        const config = await response.json();
        displayRules(config.rules || []);
    } catch (error) {
        console.error('加载规则失败:', error);
    }
}

// 切换规则启用/禁用状态
async function toggleRuleEnabled(index) {
    try {
        const response = await fetch(`/api/rules/${index}/toggle`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
        
        if (response.ok) {
            loadRules();
        } else {
            alert('切换状态失败');
        }
    } catch (error) {
        console.error('切换状态失败:', error);
        alert('切换状态失败');
    }
}

// 编辑规则
async function editRule(index) {
    try {
        const response = await fetch('/api/config');
        const config = await response.json();
        const rule = config.rules[index];
        
        currentEditIndex = index;
        document.getElementById('modal-title').textContent = '编辑规则';
        document.getElementById('pattern').value = rule.pattern || '';
        document.getElementById('pattern_type').value = rule.pattern_type || 'string';
        document.getElementById('enabled').value = rule.enabled !== false ? 'true' : 'false';
        
        // 判断规则类型
        const isMockRule = rule.type === 'mock' || rule.mock_response;
        document.getElementById('rule_type').value = isMockRule ? 'mock' : 'proxy';
        
        if (isMockRule) {
            // 填充Mock规则字段
            const mockResponse = rule.mock_response || {};
            document.getElementById('mock_status').value = mockResponse.status || 200;
            document.getElementById('mock_content_type').value = mockResponse.content_type || 'application/json';
            
            if (mockResponse.content_file) {
                document.getElementById('mock_data_source').value = 'file';
                document.getElementById('mock_content_file').value = mockResponse.content_file;
                document.getElementById('mock_content').value = '';
            } else {
                document.getElementById('mock_data_source').value = 'inline';
                document.getElementById('mock_content').value = mockResponse.content || '';
                document.getElementById('mock_content_file').value = '';
            }
            
            // 填充自定义头部
            const headers = mockResponse.headers || {};
            document.getElementById('mock_headers').value = Object.keys(headers).length > 0 ? JSON.stringify(headers, null, 2) : '';
        } else {
            // 填充代理规则字段
            document.getElementById('strip_prefix').value = rule.strip_prefix || '';
            document.getElementById('scheme').value = rule.target?.scheme || 'http';
            document.getElementById('host').value = rule.target?.host || '';
            document.getElementById('port').value = rule.target?.port || '';
        }
        
        toggleRuleTypeFields();
        toggleMockDataFields();
        togglePatternTypeFields(); // 添加对匹配类型字段的处理
        document.getElementById('rule-modal').style.display = 'block';
    } catch (error) {
        console.error('加载规则失败:', error);
    }
}

// 删除规则
async function deleteRule(index) {
    if (confirm('确定要删除这条规则吗？')) {
        try {
            const response = await fetch(`/api/rules/${index}`, { method: 'DELETE' });
            if (response.ok) {
                loadRules();
            } else {
                alert('删除失败');
            }
        } catch (error) {
            console.error('删除失败:', error);
            alert('删除失败');
        }
    }
}

// 加载规则选项到过滤器
async function loadRuleOptions() {
    try {
        const response = await fetch('/api/config');
        const config = await response.json();
        const ruleFilter = document.getElementById('log-rule-filter');
        
        // 清空现有选项（保留"全部规则"）
        ruleFilter.innerHTML = '<option value="">全部规则</option>';
        
        // 添加规则选项
        (config.rules || []).forEach((rule, index) => {
            const option = document.createElement('option');
            option.value = rule.pattern;
            option.textContent = rule.pattern;
            ruleFilter.appendChild(option);
        });
    } catch (error) {
        console.error('加载规则选项失败:', error);
    }
}

// 加载日志
async function loadLogs() {
    const logContent = document.getElementById('log-content');
    logContent.innerHTML = '<div class="log-loading">加载中...</div>';
    
    try {
        const ruleFilter = document.getElementById('log-rule-filter').value;
        const levelFilter = document.getElementById('log-level-filter').value;
        const dateFilter = document.getElementById('log-date-filter').value;
        
        const params = new URLSearchParams();
        if (ruleFilter) params.append('rule', ruleFilter);
        if (levelFilter) params.append('level', levelFilter);
        if (dateFilter) params.append('date', dateFilter);
        
        const response = await fetch(`/api/logs?${params.toString()}`);
        const data = await response.json();
        
        displayLogs(data.logs || []);
    } catch (error) {
        console.error('加载日志失败:', error);
        logContent.innerHTML = '<div class="log-empty">加载日志失败</div>';
    }
}

// 证书相关API调用
async function checkCertificateStatus() {
    const statusInfo = document.getElementById('cert-status-info');
    statusInfo.innerHTML = '检查中...';
    
    try {
        const response = await fetch('/api/cert/status');
        const data = await response.json();
        
        if (data.exists) {
            statusInfo.innerHTML = `
                <div style="color: #28a745;">
                    ✅ 证书文件已存在<br>
                    📍 位置: ${data.path}<br>
                    📅 创建时间: ${data.created_at}
                </div>
            `;
            document.getElementById('cert-path').textContent = data.path;
        } else {
            statusInfo.innerHTML = `
                <div style="color: #dc3545;">
                    ❌ 证书文件不存在<br>
                    💡 请先启动代理服务器生成证书
                </div>
            `;
        }
    } catch (error) {
        console.error('检查证书状态失败:', error);
        statusInfo.innerHTML = `
            <div style="color: #dc3545;">
                ❌ 检查证书状态失败
            </div>
        `;
    }
}

async function downloadCertificate() {
    try {
        const response = await fetch('/api/cert/download');
        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'mitmproxy-ca-cert.pem';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        } else {
            alert('下载失败');
        }
    } catch (error) {
        console.error('下载失败:', error);
        alert('下载失败');
    }
}